<?php
namespace Core\Plugin;

use Phalcon\DI;
use Core\Plugin\Zip;

/**
 * File class.
 */
class File
{

    protected $objPHPExcel;

    /**
     * excel自动下载
     *
     * @param   array  $param      ['count'=>123,'sql'=>'','header'=>['id','name'],'file'=>'filename']
     * @param   obj  $obj 
     * @param   int  $unit    每个excel条数
     */
    public function autoDownExcel($param,$obj,$unit=10000){
        set_time_limit(0);
        if($param['count'] == 0){
            return false;
        }
        if($param['count'] > $unit){
            $path = time();
            $url = PUBLIC_PATH."static".DS."excel".DS.$path;
            if(!mkdir($url)){
                echo "操作失败";die;
            }
            for ($i=1; $i <= ceil($param['count']/$unit); $i++) { 
                $list = DI::getDefault()->get('db')->fetchAll($param['sql']." limit ".$unit." offset ".($unit*($i-1)));
                if(method_exists($obj,"formatData")){
                    $list = $obj->formatData($list,$param['header']);
                }
                $this->exportExcel($param['header'],$list,$param['file'].'-'.$i,1,$path);
                unset($list);
            }
            $zobj = new Zip();
            $zobj->ZipAndDownload($url,$param['file']);
            $this->removeDir($url);
        }else{
            $list = DI::getDefault()->get('db')->fetchAll($param['sql']);
            if(method_exists($obj,"formatData")){
                $list = $obj->formatData($list,$param['header']);
            }
            $this->exportExcel($param['header'],$list,$param['file']);
        }

    }

    /**
     * excel下载
     *
     * @param   array  $header      ['id','name']
     * @param   array  $list        [['1','tony1'],['2','tony2']]
     * @param   string  $file_name    filename
     * @param   bool  $tar    1 是否需要压缩
     * @param   string  $tmp    压缩目录
     */
    public function exportExcel($header,$list,$file_name=null,$tar=false,$tmp='tmp'){
        $this->objPHPExcel = new \PHPExcel();
        $file_name = $file_name.'_'.date('YmdHi');
        if(!$tar){
            $this->exportHeader( $file_name );
        }
        $this->export($header,1);
        $pRow = 2;
        if($list){
            foreach ($list as $content) {
                $this->export( $content,$pRow);
                $pRow++;
            }
        }
        $this->finish_export($tar,$file_name,$tmp);
    }

    public function downFile($filename='',$file){
        header('Content-Type: application/octet-stream');
        $file_name = ($filename ? $filename : time()).'.'.pathinfo($file, PATHINFO_EXTENSION);
        $encoded_filename = str_replace("+", "%20", urlencode($file_name));
        $ua = $_SERVER['HTTP_USER_AGENT'];
        if (preg_match('/MSIE/', $ua)) {
            header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
        } else if (preg_match('/Firefox$/', $ua)) {
            header('Content-Disposition: attachment; filename*="utf8\'\'' . $file_name . '"');
        } else {
            header('Content-Disposition: attachment; filename="' . $file_name . '"');
        }
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        echo readfile($file);
    }

    public function removeDir($dirName){   
        if(!is_dir($dirName)){   
            return false;   
        }   
        $handle = @opendir($dirName);   
        while(($file = @readdir($handle)) !== false){   
            if($file != '.' && $file != '..'){   
                $dir = $dirName . '/' . $file;   
                is_dir($dir) ? removeDir($dir) : @unlink($dir);   
            }   
        }   
        closedir($handle);   
        return rmdir($dirName) ;   
    }  

    private function exportHeader($filename){
        ob_end_clean();//清除缓冲区,避免乱码
        header('Content-Type: application/vnd.ms-excel');
        $file_name = $filename.'.xlsx';
        $encoded_filename = str_replace("+", "%20", urlencode($file_name));
        $ua = $_SERVER['HTTP_USER_AGENT'];
        if (preg_match('/MSIE/', $ua)) {
            header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
        } else if (preg_match('/Firefox$/', $ua)) {
            header('Content-Disposition: attachment; filename*="utf8\'\'' . $file_name . '"');
        } else {
            header('Content-Disposition: attachment; filename="' . $file_name . '"');
        }
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');

    }

    private function export($data,$offset){
        $data = array_values($data);
        foreach($data as $pColumn=>$pValue){
             $this->objPHPExcel->setActiveSheetIndex(0)
            ->setCellValueExplicitByColumnAndRow($pColumn, $offset, $pValue);
        }

    }

    private function finish_export($tar=false,$file=false,$tmp){
        $objWriter = \PHPExcel_IOFactory::createWriter($this->objPHPExcel , 'Excel2007');
        if(!$tar){
            $objWriter->save('php://output');
        }else{
            $objWriter->save(PUBLIC_PATH."static".DS."excel".DS.$tmp.DS.$file.'.xlsx');
        }
    }

}